package com.gexiaobao.pigeon.ui.fragment.setting

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.view.animation.AnimationUtils
import android.widget.Button
import android.widget.LinearLayout
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.core.widget.NestedScrollView
import androidx.fragment.app.setFragmentResult
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.codingending.popuplayout.PopupLayout
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.ext.Constant
import com.gexiaobao.pigeon.app.ext.showMessage
import com.gexiaobao.pigeon.app.model.bean.AddressListResponse
import com.gexiaobao.pigeon.app.model.bean.ProvinceEntity
import com.gexiaobao.pigeon.app.model.param.ShippingAddressParams
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.databinding.FragmentAddReceiveAddressBinding
import com.gexiaobao.pigeon.ui.adapter.AreaAdapter
import com.gexiaobao.pigeon.ui.adapter.CityAdapter
import com.gexiaobao.pigeon.ui.adapter.HotCityAdapter
import com.gexiaobao.pigeon.ui.adapter.ProvinceAdapter
import com.gexiaobao.pigeon.ui.adapter.ProvinceAdapter2
import com.gexiaobao.pigeon.ui.adapter.StreetAdapter
import com.gexiaobao.pigeon.viewmodel.SettingViewModel
import com.github.promeg.pinyinhelper.Pinyin
import com.github.promeg.tinypinyin.lexicons.android.cncity.CnCityDict
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.yokeyword.indexablerv.IndexableLayout


/**
 * @Author      : hxw
 * @Date        : 2023/5/31 18:44
 * @Describe    : 添加收货地址
 */
class FragmentAddReceiveAddress : BaseFragment<SettingViewModel, FragmentAddReceiveAddressBinding>() {

    private lateinit var mDatas: ArrayList<ProvinceEntity>
    private var tvProvince: AppCompatTextView? = null
    private var tvStreet: AppCompatTextView? = null
    private var llChooseAddress: LinearLayout? = null
    private var tvCity: AppCompatTextView? = null
    private var tvArea: AppCompatTextView? = null
    private var nscrProvince: NestedScrollView? = null
    private var recyclerViewCity: RecyclerView? = null
    private var recyclerViewArea: RecyclerView? = null
    private var recyclerViewStreet: RecyclerView? = null
    private var mAddressType = 0
    private var id = 0
    private var provinceId = 0
    private var cityId = 0
    private var areaId = 0
    private var provinceName = ""
    private var cityName = ""
    private var areaName = ""
    private var streetName = ""
    private var isChooseSure = false
    private var isDistrict = false//是否是直辖市或特别行政区

    private val mAdapter: ProvinceAdapter by lazy { ProvinceAdapter(arrayListOf()) }
    private val mCityAdapter: CityAdapter by lazy { CityAdapter(arrayListOf()) }
    private val mAreaAdapter: AreaAdapter by lazy { AreaAdapter(arrayListOf()) }
    private val mStreetAdapter: StreetAdapter by lazy { StreetAdapter(arrayListOf()) }
    private val hotCityAdapter: HotCityAdapter by lazy { HotCityAdapter(arrayListOf()) }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        activity?.let { StatusBarUtil.setLightMode(it) }
        activity?.let { StatusBarUtil.setColor(it, Color.TRANSPARENT, 0) }
    }

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.viewmodel = mViewModel
        mDatabind.switchCompatBtn.setOnCheckedChangeListener { _, isChecked ->
            mAddressType = if (isChecked) {
                1
            } else {
                2
            }
        }
        val type = arguments?.getString("type").toString()
        if (type == "modify") {
            mDatabind.includeBar.tvWhiteTitle.text = "编辑收货地址"
            val data = arguments?.getParcelable<AddressListResponse.ListBean>(Constant.DATA_BEAN)
            if (data != null) {
                id = data.id
                mViewModel.addReceiveAddressName.set(data.name)
                mViewModel.addReceiveAddressMobile.set(data.mobile)
                mViewModel.addReceiveAddressArea.set(data.address)
                mViewModel.addReceiveAddressDetail.set(data.detailedAddress)
                mDatabind.switchCompatBtn.isChecked = data.addressType == 1
            }
        } else {
            mDatabind.includeBar.tvWhiteTitle.text = "添加收货地址"
        }
    }

    override fun lazyLoadData() {
        super.lazyLoadData()
        mViewModel.getProvinceList()
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.includeBar.ivBack,
            mDatabind.mineSettingReceiveAddCommit,
            mDatabind.mineSettingReceiveAddAddressChoice,
            mDatabind.mineSettingReceiveAddAddress,
        ) {
            when (it) {
                mDatabind.includeBar.ivBack -> {
                    nav().navigateUp()
                }

                mDatabind.mineSettingReceiveAddCommit -> {
                    commitAddressData()
                }

                mDatabind.mineSettingReceiveAddAddress, mDatabind.mineSettingReceiveAddAddressChoice -> {
                    showBottomViewAddress()
//                    startActivity<ActivityPickAddress>("list" to mDatas)
                }
            }
        }
    }

    private lateinit var mAdapterPro: ProvinceAdapter2

    @SuppressLint("SetTextI18n", "MissingInflatedId")
    private fun showBottomViewAddress() {
        val parent = View.inflate(context, R.layout.bottom_address_list, null)
        val popupLayout = PopupLayout.init(context, parent)
        val recyclerView = parent.findViewById<RecyclerView>(R.id.recyclerViewProvince)
        val recyclerViewHotCity = parent.findViewById<RecyclerView>(R.id.recyclerViewHotCity)
        val ivCloseBottomCity = parent.findViewById<AppCompatImageView>(R.id.ivCloseBottomCity)
        val indexAble = parent.findViewById<IndexableLayout>(R.id.indexAble)
        llChooseAddress = parent.findViewById(R.id.llChooseAddress)
        tvProvince = parent.findViewById(R.id.tvProvince)
        tvCity = parent.findViewById(R.id.tvCity)
        tvArea = parent.findViewById(R.id.tvArea)
        tvStreet = parent.findViewById(R.id.tvStreet)
//        nscrProvince = parent.findViewById(R.id.nscrProvince)
        recyclerViewCity = parent.findViewById(R.id.recyclerViewCity)
        recyclerViewArea = parent.findViewById(R.id.recyclerViewArea)
        recyclerViewStreet = parent.findViewById(R.id.recyclerViewStreet)

        if (isChooseSure) {
            /** 判断：isChooseSure =true:已经选中过完整地址，false:没有选中过完整地址 */
            llChooseAddress!!.isVisible = true
            tvProvince!!.isVisible = true
            tvArea!!.isVisible = true
            tvStreet!!.isVisible = true
            tvCity!!.isVisible = cityName.isNotEmpty()
            tvStreet!!.setTextColor(ContextCompat.getColor(requireContext(), R.color.color_fe4542))
            tvProvince!!.text = provinceName
            tvCity!!.text = cityName
            tvArea!!.text = areaName
            tvStreet!!.text = streetName
            recyclerViewStreet!!.isVisible = true
        }

        /** 省列表 */
        indexAble.setLayoutManager(LinearLayoutManager(context))
        // 多音字处理
        Pinyin.init(Pinyin.newConfig().with(CnCityDict.getInstance(context)))
        mAdapterPro = context?.let { ProvinceAdapter2(it) }!!
        indexAble.setAdapter(mAdapterPro)
        indexAble.setOverlayStyle_Center()
        mAdapterPro.setDatas(mDatas)
        //全字母排序。  排序规则设置为：每个字母都会进行比较排序；速度较慢
        indexAble.setCompareMode(IndexableLayout.MODE_FAST)

        /** 省列表 */
        recyclerView.layoutManager = LinearLayoutManager(context)
        recyclerView.adapter = mAdapter

        /** 市列表 */
        recyclerViewCity!!.layoutManager = LinearLayoutManager(context)
        recyclerViewCity!!.adapter = mCityAdapter

        /** 区列表 */
        recyclerViewArea!!.layoutManager = LinearLayoutManager(context)
        recyclerViewArea!!.adapter = mAreaAdapter

        /** 街道列表 */
        recyclerViewStreet!!.layoutManager = LinearLayoutManager(context)
        recyclerViewStreet!!.adapter = mStreetAdapter

        /** 热门城市列表 */
        recyclerViewHotCity.layoutManager = GridLayoutManager(context, 4)
        recyclerViewHotCity.adapter = hotCityAdapter

        ivCloseBottomCity.setOnClickListener {
            popupLayout.dismiss()
        }

        mAdapterPro.setOnItemContentClickListener { _, _, _, entity ->
            setIds(
                1,
                entity.name,
                entity.provinceId,
                entity.cityId,
                entity.areaId
            )
            if (provinceName == "北京市" || provinceName == "上海市" || provinceName == "重庆市" || provinceName == "天津市" || provinceName == "香港特别行政区" || provinceName == "澳门特别行政区") {
                mViewModel.getAreaList(provinceId, cityId)
                isDistrict = true
            } else {
                isDistrict = false
                mViewModel.getCityList(provinceId)
            }
        }

        mAdapter.setOnItemClickListener { _, _, position ->
            setIds(
                1,
                mAdapter.data[position].name,
                mAdapter.data[position].provinceId,
                mAdapter.data[position].cityId,
                mAdapter.data[position].areaId
            )
            if (provinceName == "北京市" || provinceName == "上海市" || provinceName == "重庆市" || provinceName == "天津市" || provinceName == "香港特别行政区" || provinceName == "澳门特别行政区") {
                mViewModel.getAreaList(provinceId, cityId)
                isDistrict = true
            } else {
                isDistrict = false
                mViewModel.getCityList(provinceId)
            }
        }

        mCityAdapter.setOnItemClickListener { _, _, position ->
            setIds(
                2,
                mCityAdapter.data[position].name,
                mCityAdapter.data[position].provinceId,
                mCityAdapter.data[position].cityId,
                mCityAdapter.data[position].areaId
            )
        }

        mAreaAdapter.setOnItemClickListener { _, _, position ->
            setIds(
                3,
                mAreaAdapter.data[position].name,
                mAreaAdapter.data[position].provinceId,
                mAreaAdapter.data[position].cityId,
                mAreaAdapter.data[position].areaId
            )
        }

        mStreetAdapter.setOnItemClickListener { _, _, position ->
            isChooseSure = true
            streetName = mStreetAdapter.data[position].name
            if (isDistrict) {
                mDatabind.mineSettingReceiveAddAddress.text = "$provinceName-$areaName-$streetName"
            } else {
                mDatabind.mineSettingReceiveAddAddress.text = "$provinceName-$cityName-$areaName-$streetName"
            }
            cityName = ""
            popupLayout.dismiss()
        }

        hotCityAdapter.setOnItemClickListener { _, _, position ->
            val name = hotCityAdapter.data[position].name
            isDistrict =
                name == "北京市" || name == "上海市" || name == "重庆市" || name == "天津市" || name == "香港特别行政区" || name == "澳门特别行政区"
            provinceName = hotCityAdapter.data[position].pName
            setIds(
                4,
                hotCityAdapter.data[position].name,
                hotCityAdapter.data[position].provinceId,
                hotCityAdapter.data[position].cityId,
                hotCityAdapter.data[position].areaId
            )
        }

        tvProvince!!.setOnClickListener {
            setHideRecycler(1)
        }
        tvCity!!.setOnClickListener {
            tvCity!!.setTextColor(ContextCompat.getColor(requireContext(), R.color.color_fe4542))
            setHideRecycler(2)
        }
        tvArea!!.setOnClickListener {
            tvArea!!.setTextColor(ContextCompat.getColor(requireContext(), R.color.color_fe4542))
            setHideRecycler(3)
        }
        tvStreet!!.setOnClickListener {
            tvStreet!!.setTextColor(ContextCompat.getColor(requireContext(), R.color.color_fe4542))
            setHideRecycler(4)
        }

        popupLayout.setHeight(getWindowHeight(), true)//手动设置弹出布局的高度
        popupLayout.setUseRadius(true)
        popupLayout.show(PopupLayout.POSITION_BOTTOM)
    }

    /**
     * 设置recyclerView的隐藏机制
     * @param type 1省份，2城市 3区/县 4街道
     */
    private fun setHideRecycler(type: Int) {
        when (type) {
            1 -> {
                tvProvince!!.setTextColor(ContextCompat.getColor(requireContext(), R.color.color_fe4542))
                tvCity!!.setTextColor(ContextCompat.getColor(requireContext(), R.color.comm_text_gray_dark))
                tvArea!!.setTextColor(ContextCompat.getColor(requireContext(), R.color.comm_text_gray_dark))
                tvStreet!!.setTextColor(ContextCompat.getColor(requireContext(), R.color.comm_text_gray_dark))
//                nscrProvince!!.isVisible = true
                recyclerViewCity!!.isVisible = false
                recyclerViewCity!!.animation = AnimationUtils.makeOutAnimation(context, true)
                recyclerViewArea!!.isVisible = false
                recyclerViewArea!!.animation = AnimationUtils.makeOutAnimation(context, true)
                recyclerViewStreet!!.isVisible = false
                recyclerViewStreet!!.animation = AnimationUtils.makeOutAnimation(context, true)
            }

            2 -> {
                tvProvince!!.setTextColor(ContextCompat.getColor(requireContext(), R.color.comm_text_gray_dark))
                tvCity!!.setTextColor(ContextCompat.getColor(requireContext(), R.color.color_fe4542))
                tvArea!!.setTextColor(ContextCompat.getColor(requireContext(), R.color.comm_text_gray_dark))
                tvStreet!!.setTextColor(ContextCompat.getColor(requireContext(), R.color.comm_text_gray_dark))
                recyclerViewCity!!.isVisible = true
                recyclerViewArea!!.isVisible = false
                recyclerViewArea!!.animation = AnimationUtils.makeOutAnimation(context, true)
                recyclerViewStreet!!.isVisible = false
                recyclerViewStreet!!.animation = AnimationUtils.makeOutAnimation(context, true)
            }

            3 -> {
                tvProvince!!.setTextColor(ContextCompat.getColor(requireContext(), R.color.comm_text_gray_dark))
                tvCity!!.setTextColor(ContextCompat.getColor(requireContext(), R.color.comm_text_gray_dark))
                tvArea!!.setTextColor(ContextCompat.getColor(requireContext(), R.color.color_fe4542))
                tvStreet!!.setTextColor(ContextCompat.getColor(requireContext(), R.color.comm_text_gray_dark))
                recyclerViewArea!!.isVisible = true
                recyclerViewStreet!!.isVisible = false
                recyclerViewStreet!!.animation = AnimationUtils.makeOutAnimation(context, true)
            }

            4 -> {
                tvProvince!!.setTextColor(ContextCompat.getColor(requireContext(), R.color.comm_text_gray_dark))
                tvCity!!.setTextColor(ContextCompat.getColor(requireContext(), R.color.comm_text_gray_dark))
                tvArea!!.setTextColor(ContextCompat.getColor(requireContext(), R.color.comm_text_gray_dark))
                tvStreet!!.setTextColor(ContextCompat.getColor(requireContext(), R.color.color_fe4542))
                recyclerViewStreet!!.isVisible = true
                recyclerViewStreet!!.animation = AnimationUtils.makeInAnimation(context, false)//从右侧滑入
            }
        }
    }

    /** 设置省市区的id */
    private fun setIds(type: Int, name: String, pId: Int, cId: Int, aId: Int) {
        provinceId = pId
        cityId = cId
        areaId = aId
        when (type) {
            1 -> {//省份
                provinceName = name
                tvProvince!!.text = provinceName
                setTextAndColor(tvCity!!)
                tvProvince!!.setTextColor(ContextCompat.getColor(requireContext(), R.color.comm_text_gray_dark))
                llChooseAddress!!.isVisible = true
                tvProvince!!.isVisible = true
                tvArea!!.isVisible = false
                tvStreet!!.isVisible = false
            }

            2 -> {//城市
                cityName = name
                tvCity!!.text = cityName
                //获取-区
                mViewModel.getAreaList(provinceId, cityId)
                setTextAndColor(tvArea!!)
                tvCity!!.setTextColor(ContextCompat.getColor(requireContext(), R.color.comm_text_gray_dark))
                tvStreet!!.isVisible = false
                llChooseAddress!!.isVisible = true
                tvProvince!!.isVisible = true
                tvCity!!.isVisible = !isDistrict
            }

            3 -> {//地区
                areaName = name
                //获取街道信息
                mViewModel.getTownList(provinceId, cityId, areaId)
                tvArea!!.isVisible = true
                tvArea!!.text = areaName
                tvArea!!.setTextColor(ContextCompat.getColor(requireContext(), R.color.comm_text_gray_dark))
                setTextAndColor(tvStreet!!)
                llChooseAddress!!.isVisible = true
                tvProvince!!.isVisible = true
                tvCity!!.isVisible = !isDistrict
            }

            4 -> {//热门城市
                cityName = name
                mViewModel.getAreaList(provinceId, cityId)
                tvProvince!!.isVisible = true
                tvProvince!!.text = provinceName
                tvProvince!!.setTextColor(ContextCompat.getColor(requireContext(), R.color.comm_text_gray_dark))
                tvCity!!.isVisible = false
                llChooseAddress!!.isVisible = true
                setTextAndColor(tvArea!!)
            }
        }
    }

    private fun setTextAndColor(tv: AppCompatTextView) {
        tv.isVisible = true
        tv.text = "请选择"
        tv.setTextColor(ContextCompat.getColor(requireContext(), R.color.color_fe4542))
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun createObserver() {
        super.createObserver()
        /** 获取街道列表 */
        mViewModel.streetListResult.observe(viewLifecycleOwner) {
            mStreetAdapter.setList(it.list)
            mStreetAdapter.notifyDataSetChanged()
            recyclerViewStreet!!.isVisible = true
            recyclerViewStreet!!.animation = AnimationUtils.makeInAnimation(context, false)//从右侧滑入
        }
        /** 获取地区列表 */
        mViewModel.areaListResult.observe(viewLifecycleOwner) {
            mAreaAdapter.setList(it.list)
            mAreaAdapter.notifyDataSetChanged()
            recyclerViewArea!!.isVisible = true
            recyclerViewArea!!.animation = AnimationUtils.makeInAnimation(context, false)//从右侧滑入
        }
        /** 获取城市列表 */
        mViewModel.cityListResult.observe(viewLifecycleOwner) {
            mCityAdapter.setList(it.list)
            mCityAdapter.notifyDataSetChanged()
            recyclerViewCity!!.isVisible = true
            recyclerViewCity!!.animation = AnimationUtils.makeInAnimation(context, false)//从右侧滑入
        }
        /** 获取省份列表 */
        mViewModel.provinceListResult.observe(viewLifecycleOwner) { it ->
            mAdapter.setList(it.list)
            mAdapter.notifyDataSetChanged()
            hotCityAdapter.setList(it.hotCityList)
            hotCityAdapter.notifyDataSetChanged()

            mDatas = ArrayList()
            it.list.forEach {
                mDatas.add(ProvinceEntity(it.areaId, it.cityId, it.id, it.name, it.provinceId))
            }
        }
        /** 编辑收货地址 */
        mViewModel.editAddressResult.observe(viewLifecycleOwner) {
            dismissLoadingAntiShake()
            if (it.isSuccess) {
                setFragmentResult("editSuccess", Bundle().apply {
                    putBoolean("isSuccess", true)
                })
                eventViewModel.toRefreshData.value = true
                nav().navigateUp()
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
    }

    private fun commitAddressData() {
        when {
            mViewModel.addReceiveAddressName.get().isEmpty() -> showMessage("请填写收货人")
            mViewModel.addReceiveAddressMobile.get().isEmpty() -> showMessage("请填写电话")
            !Util.isTelPhoneNumber(mViewModel.addReceiveAddressMobile.get().trim()) -> showMessage(
                resources.getString(
                    R.string.user_phone_number_wrong
                )
            )

            mViewModel.addReceiveAddressArea.get().isEmpty() -> showMessage("请完善所在地区和详细地址")
            mViewModel.addReceiveAddressDetail.get().isEmpty() -> showMessage("请完善所在地区和详细地址")
            else -> {
                val body = ShippingAddressParams(
                    id = id,
                    name = mViewModel.addReceiveAddressName.get().trim(),
                    mobile = mViewModel.addReceiveAddressMobile.get().trim(),
                    address = mViewModel.addReceiveAddressArea.get().trim(),
                    detailedAddress = mViewModel.addReceiveAddressDetail.get().trim(),
                    addressType = mAddressType
                )
                showLoadingAntiShake(getString(R.string.loading))
                mViewModel.editShippingAddress(body)
            }
        }
    }

    /**
     * 计算高度(初始化可以设置默认高度)
     *
     * @return
     */
    private fun getWindowHeight(): Int {
        val res = this.resources
        val displayMetrics = res.displayMetrics
        val heightPixels = displayMetrics.heightPixels
        //设置弹窗高度为屏幕高度的2/3
        return heightPixels / 3 - 50
    }
}
